import { Checkbox } from 'antd';
import React, { useState, useRef} from 'react';
import ProTable from '@ant-design/pro-table';
import { getPermitionList, updatePermitionList } from './service';

const TableList = () => {
  const actionRef = useRef();
  const functionName = [
    { function: '预约管理', name:'Task' },
    { function: '任务标签管理', name:'TskTag' },
    { function: '人员管理', name:'SysMember' },
    { function: '车辆管理', name:'Car' },
    { function: '维保管理', name:'Maintenance' },
    { function: '用户配置', name:'Permitions' },
    { function: '统计页面', name:'Statistics' },
  ];
  const userList = [];
  const [currentUser, setCurrentUser] = useState('1');
  function isChange (record, type) {
    let isActive = 0;
    let permitionName = '';
    if (type == 'list' && record.name == 'Permitions') {
      permitionName = 'listAllPermitions';
    } else {
      permitionName = type + record.name;
    }
    switch (type) {
      case 'list':
        if(record.list == 1) {
          isActive = 2;
        } else if(record.list == 2) {
          isActive = 1;
        }
        break;
      case 'detail':
        if(record.detail == 1) {
          isActive = 2;
        } else if(record.detail == 2) {
          isActive = 1;
        }
        break;
      case 'add':
        if(record.add == 1) {
          isActive = 2;
        } else if(record.add == 2) {
          isActive = 1;
        }
        break;
      case 'update':
        if(record.update == 1) {
          isActive = 2;
        } else if(record.update == 2) {
          isActive = 1;
        }
        break;
      case 'delete':
        if(record.delete == 1) {
          isActive = 2;
        } else if(record.delete == 2) {
          isActive = 1;
        }
        break;
      case 'verify':
        if(record.verify == 1) {
          isActive = 2;
        } else if(record.verify == 2) {
          isActive = 1;
        }
        break;
    }

    updatePermitionList({type: changeUserType(), permitionName: permitionName, is_active: isActive}).then((data) => {
      let res = data;
      if (res.code == '200') {
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
    });
    console.log('isChange: '+JSON.stringify(record));
  };
  function changeUserType() {
    let type = 1;
    switch(parseInt(currentUser)) {
      case 1:
        type = 2;
        break;
      case 2:
        type = 3;
        break;
      case 3:
        type = 1;
        break;
    }
    return type;
  }
  const [activekey, setActiveKey] = useState('1');
  const renderBadge = (count, active = false) => {
    return (
      <text
        style={{
          marginTop: -2,
          marginLeft: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };

  const columns = [
    {
      title: '功能',
      dataIndex: 'function',
      search: false,
    },
    {
      title: '查看列表',
      search: false,
      dataIndex: 'list',
      render: (_, record) => [
        <Checkbox key="list" checked={record.list == '1'} disabled={record.list == '-1' || record.list == undefined} onClick={() => isChange(record, 'list')}/>
      ],
    },
    {
      title: '查看详情',
      search: false,
      dataIndex: 'detail',
      render: (_, record) => [
        <Checkbox key="detail" checked={record.detail == '1'} disabled={record.detail == '-1' || record.detail == undefined} onClick={() => isChange(record, 'detail')}/>
      ],
    },
    {
      title: '新增',
      search: false,
      dataIndex: 'add',
      render: (_, record) => [
        <Checkbox key="add" checked={record.add == '1'} disabled={record.add == '-1' || record.add == undefined} onClick={() => isChange(record, 'add')}/>
      ],
    },
    {
      title: '修改',
      search: false,
      dataIndex: 'update',
      render: (_, record) => [
        <Checkbox key="update" checked={record.update == '1'} disabled={record.update == '-1' || record.update == undefined} onClick={() => isChange(record, 'update')}/>
      ],
    },
    {
      title: '删除',
      search: false,
      dataIndex: 'delete',
      render: (_, record) => [
        <Checkbox key="delete" checked={record.delete == '1'} disabled={record.delete == '-1' || record.delete == undefined} onClick={() => isChange(record, 'delete')}/>
      ],
    },
    {
      title: '审批',
      search: false,
      dataIndex: 'verify',
      render: (_, record) => [
        <Checkbox key="verify" checked={record.verify == '1'} disabled={record.verify == '-1' || record.verify == undefined} onClick={() => isChange(record, 'verify')}/>
      ],
    },
  ];
  return (
    <>
     <ProTable
        actionRef={actionRef}
        rowKey="key"
        search={false}
        request={async (params, sorter, filter) => {
          try{
            const res = await getPermitionList({});
            var n = 0;
            console.log('request userList: ' + userList.length);
            console.log('-------------------------')
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i];  
              if (changeUserType() == element.type) {
                userList[n] = element;
                console.log("request element: " + JSON.stringify(element))
                n++; 
              }
            }
            
            for (let j = 0; j < functionName.length; j++) {
              const element = functionName[j];
              const funName = element.name;
              if (j <= 4) {
                for (let k = 0; k < userList.length; k++) {
                  let functionname = userList[k].functionname;
                  if (functionname.indexOf('list') != -1 && functionname.indexOf(funName) != -1) {
                    console.log('request  funName: ' + functionname + '/ ' + j);
                    element.list = userList[k].is_active;
                  }
                  if (functionname.indexOf('detail') != -1 && functionname.indexOf(funName) != -1) {
                    element.detail = userList[k].is_active;
                    if (funName == 'Permitions') {
                      element.detail = '-1';
                    }
                  }
                  if (functionname.indexOf('add') != -1 && functionname.indexOf(funName) != -1) {
                    element.add = userList[k].is_active;
                    if (funName == 'Permitions' || funName == 'Car') {
                      element.add = '-1';
                    }
                  }
                  if (functionname.indexOf('update') != -1 && functionname.indexOf(funName) != -1) {
                    element.update = userList[k].is_active;
                    if (funName == 'Cars') {
                      element.update = '-1';
                    }
                  }
                  if (functionname.indexOf('delete') != -1 && functionname.indexOf(funName) != -1) {
                    element.delete = userList[k].is_active;
                    if (funName == 'Permitions' || funName == 'Car') {
                      element.delete = '-1';
                    }
                  }
                  if (functionname.indexOf('verify') != -1 && functionname.indexOf(funName) != -1) {
                    element.verify = userList[k].is_active;
                  }
                }
              } else {
                element.list = '-1';
                element.detail = '-1';
                element.add = '-1';
                element.update = '-1';
                element.delete = '-1';
                element.verify = '-1';
              }
            }
            for (let index = 0; index < functionName.length; index++) {
              const element = functionName[index];
              console.log('request functionName: ' + JSON.stringify(element));
            }
            return {data: functionName || [], success: true, total: res.total || 0}
          }catch(error){
            return { data: [], success: false, total: 0}
          }
        }}
        columns={columns}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activekey,
            items: [
              {
                key: '1',
                label: <span>基础用户{renderBadge(99, activekey === '1')}</span>,
              },
              {
                key: '2',
                label: <span>普通用户{renderBadge(30, activekey === '2')}</span>,
              },
              {
                key: '3',
                label: <span>管理员{renderBadge(30, activekey === '3')}</span>,
              },
            ],
            onChange: (key) => {
              setCurrentUser(key)
              setActiveKey(key);
              if(actionRef.current) {
                actionRef.current.reload();
              }
            },
          },
          actions: [
          ],
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共有 ${total} 条记录`,
          pageSize:10,
        }}
      />
    </>
  );
};

export default TableList;
